import PageWrapper from "@/components/PageWrapper";
import { getComponent } from "@/components/QuestionComponents";
import getQuestionById from "@/services/question";
import styles from "../question.module.scss";
import { Form } from "antd";

type PropsType = {
  code: number;
  message?: string;
  result?: {
    id: string;
    title: string;
    desc?: string;
    isDeleted?: boolean;
    isPublished?: boolean;
    componentList?: Array<any>;
  };
};

export default function Question(props: PropsType) {
  const { code, message, result } = props;
  const { title = "", desc = "", componentList = [] } = result || {};

  if (code > 0) {
    return (
      <PageWrapper title="错误">
        <div style={{ marginTop: "6rem", textAlign: "center" }}>
          <h2>错误</h2>
          <p>{message}</p>
        </div>
      </PageWrapper>
    );
  }

  const ComponentListElem = componentList.map((c) => {
    const ComponentElem = getComponent(c);
    return <div key={c.id}>{ComponentElem}</div>;
  });

  return (
    <PageWrapper title={title} desc={desc}>
      <Form layout="vertical" className={`${styles.from} ${styles.prompt}`}>
        {ComponentListElem}
      </Form>
    </PageWrapper>
  );
}

export async function getServerSideProps(context: any) {
  const { questionId } = context.params;
  const { answerId } = context.query;
  const data = await getQuestionById(questionId, true, answerId);

  return {
    props: {
      ...data,
    },
  };
}
